package StudyCode.summary.myfile;

import java.util.Stack;
import java.util.StringTokenizer;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class NormalizePathEnsureValid {

	public static void main(String[] args) {
		System.out.println(normalizePath("E:/Copy/12/"));
	}

	private static String normalizePath(String path) throws IllegalArgumentException {
		if (!path.contains("./"))
			return path;
		Stack<String> pathSegments = new Stack<String>();
		StringTokenizer tokenizer = new StringTokenizer(path, "/");
		while (tokenizer.hasMoreTokens()) {
			String pathSegment = tokenizer.nextToken();
			if (".".equals(pathSegment))
				continue;
			if ("..".equals(pathSegment)) {
				if (pathSegments.size() == 0) {
					throw new IllegalArgumentException("非法路径: " + path);
				}
				pathSegments.pop();
			} else {
				pathSegments.push(pathSegment);
			}
		}
		StringBuffer sb = new StringBuffer(path.length());
		int len = pathSegments.size();
		for (int i = 0; i < len; i++) {
			if (i != 0)
				sb.append('/');
			sb.append(pathSegments.elementAt(i));
		}
		return sb.toString();
	}
}
